package com.jx.driving.message;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

public class TransmissionMessageIdMapper {
    public static final TransmissionMessageIdMapper instance = new TransmissionMessageIdMapper();

    private Map<Integer, Class<?>> id2Class = new ConcurrentHashMap<>();

    private Map<Class<?>, Integer> class2Id = new ConcurrentHashMap<>();

    /**
     * 根据id获取消息类型
     */
    public Class<?> getClass(Integer id) {
	Class<?> clazz = id2Class.get(id);
	if (clazz != null) {
	    return clazz;
	}
	String hexadecimal = Integer.toHexString(id).toUpperCase();
	int len = 4 - hexadecimal.length();
	StringBuffer sb = new StringBuffer(4);
	for (int i = 0; i < len; i++) {
	    sb.append("0");
	}
	sb.append(hexadecimal);
	hexadecimal = sb.toString();
	String requestPackage = "com.jx.driving.transmission.Terminal0x" + hexadecimal + "Transmission";
	try {
	    clazz = Class.forName(requestPackage);
	} catch (ClassNotFoundException e) {
	    throw new RuntimeException("transmission class not found by id " + hexadecimal, e);
	}
	id2Class.put(id, clazz);
	class2Id.put(clazz, id);
	return clazz;
    }

    /**
     * 根据消息类型获取id
     */
    public Integer getId(Class<?> clazz) {
	Integer id = class2Id.get(clazz);
	if (id != null) {
	    return id;
	}
	id = Integer.parseInt(getTranCode(clazz), 16);
	class2Id.put(clazz, id);
	id2Class.put(id, clazz);
	return id;
    }

    private String getTranCode(Class<?> clazz) {
	return StringUtils.substringBetween(clazz.getName(), "Terminal0x", "Transmission");
    }
}
